// 用户隐私设置服务
import { apiService } from './api'
import type { 
  UserPrivacySetting,
  UpdatePrivacySettingRequest,
  CanBeSearchedResponse,
  CanReceiveFriendRequestResponse
} from '@/types'

export class UserPrivacyService {
  /**
   * 获取用户隐私设置
   */
  async getUserPrivacySetting(userId: number): Promise<UserPrivacySetting> {
    const response = await apiService.userGet<UserPrivacySetting>(`/api/privacy/${userId}`)
    if (!response.success || !response.data) {
      throw new Error(response.message || '获取隐私设置失败')
    }
    return response.data
  }

  /**
   * 更新用户隐私设置
   */
  async updatePrivacySetting(userId: number, request: UpdatePrivacySettingRequest): Promise<UserPrivacySetting> {
    const response = await apiService.userPut<UserPrivacySetting>(`/api/privacy/${userId}`, request)
    if (!response.success || !response.data) {
      throw new Error(response.message || '更新隐私设置失败')
    }
    return response.data
  }

  /**
   * 重置为默认隐私设置
   */
  async resetToDefault(userId: number): Promise<UserPrivacySetting> {
    const response = await apiService.userPost<UserPrivacySetting>(`/api/privacy/${userId}/reset`, {})
    if (!response.success || !response.data) {
      throw new Error(response.message || '重置隐私设置失败')
    }
    return response.data
  }

  /**
   * 检查用户是否允许被搜索
   */
  async canBeSearched(userId: number, searchType: string, searchValue: string): Promise<boolean> {
    const response = await apiService.userGet<CanBeSearchedResponse>(
      `/api/privacy/${userId}/can-be-searched?searchType=${searchType}&searchValue=${searchValue}`
    )
    if (!response.success || !response.data) {
      throw new Error(response.message || '检查搜索权限失败')
    }
    return response.data.canBeSearched
  }

  /**
   * 检查用户是否允许接收好友请求
   */
  async canReceiveFriendRequest(fromUserId: number, toUserId: number): Promise<boolean> {
    const response = await apiService.userGet<CanReceiveFriendRequestResponse>(
      `/api/privacy/${toUserId}/can-receive-friend-request?fromUserId=${fromUserId}`
    )
    if (!response.success || !response.data) {
      throw new Error(response.message || '检查好友请求权限失败')
    }
    return response.data.canReceive
  }

  /**
   * 批量更新隐私设置
   */
  async batchUpdatePrivacySettings(
    userId: number,
    settings: Partial<UpdatePrivacySettingRequest>[]
  ): Promise<UserPrivacySetting> {
    // 合并所有设置
    const mergedSettings = settings.reduce((acc, setting) => ({ ...acc, ...setting }), {})
    return this.updatePrivacySetting(userId, mergedSettings)
  }

  /**
   * 获取隐私设置摘要
   */
  async getPrivacySummary(userId: number): Promise<{
    friendRequestLevel: string
    searchRestrictions: string[]
    visibilitySettings: string[]
  }> {
    try {
      const setting = await this.getUserPrivacySetting(userId)
      
      const friendRequestLevel = this.getFriendRequestLevelDescription(setting.friendRequestPermission)
      
      const searchRestrictions = []
      if (!setting.allowSearchByPhone) searchRestrictions.push('手机号')
      if (!setting.allowSearchByEmail) searchRestrictions.push('邮箱')
      if (!setting.allowSearchByUsername) searchRestrictions.push('用户名')
      
      const visibilitySettings = []
      if (!setting.showOnlineStatus) visibilitySettings.push('隐藏在线状态')
      if (!setting.allowGroupInvite) visibilitySettings.push('禁止群组邀请')
      
      return {
        friendRequestLevel,
        searchRestrictions,
        visibilitySettings
      }
    } catch (error) {
      console.error('Error getting privacy summary:', error)
      return {
        friendRequestLevel: '未知',
        searchRestrictions: [],
        visibilitySettings: []
      }
    }
  }

  /**
   * 获取好友请求权限级别描述
   */
  private getFriendRequestLevelDescription(permission: string): string {
    switch (permission) {
      case 'EVERYONE':
        return '所有人'
      case 'FRIENDS_OF_FRIENDS':
        return '朋友的朋友'
      case 'CONTACTS_ONLY':
        return '仅联系人'
      case 'NOBODY':
        return '不允许'
      default:
        return '未知'
    }
  }

  /**
   * 检查是否为严格隐私模式
   */
  async isStrictPrivacyMode(userId: number): Promise<boolean> {
    try {
      const setting = await this.getUserPrivacySetting(userId)
      return (
        setting.friendRequestPermission === 'NOBODY' ||
        (!setting.allowSearchByPhone && !setting.allowSearchByEmail && !setting.allowSearchByUsername) ||
        (!setting.showOnlineStatus && !setting.allowGroupInvite)
      )
    } catch (error) {
      console.error('Error checking strict privacy mode:', error)
      return false
    }
  }

  /**
   * 应用推荐的隐私设置
   */
  async applyRecommendedSettings(userId: number, level: 'open' | 'balanced' | 'strict'): Promise<UserPrivacySetting> {
    let settings: UpdatePrivacySettingRequest

    switch (level) {
      case 'open':
        settings = {
          friendRequestPermission: 'EVERYONE',
          requireVerification: false,
          allowSearchByPhone: true,
          allowSearchByEmail: true,
          allowSearchByUsername: true,
          showOnlineStatus: true,
          allowGroupInvite: true
        }
        break
      case 'balanced':
        settings = {
          friendRequestPermission: 'FRIENDS_OF_FRIENDS',
          requireVerification: true,
          allowSearchByPhone: true,
          allowSearchByEmail: false,
          allowSearchByUsername: true,
          showOnlineStatus: true,
          allowGroupInvite: true
        }
        break
      case 'strict':
        settings = {
          friendRequestPermission: 'CONTACTS_ONLY',
          requireVerification: true,
          allowSearchByPhone: false,
          allowSearchByEmail: false,
          allowSearchByUsername: false,
          showOnlineStatus: false,
          allowGroupInvite: false
        }
        break
      default:
        throw new Error('无效的隐私级别')
    }

    return this.updatePrivacySetting(userId, settings)
  }
}

export const userPrivacyService = new UserPrivacyService()